package faceattendsystem.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import faceattendsystem.entity.Employee;
import faceattendsystem.service.IEmployeeService;
import faceattendsystem.serviceImpl.EmployeeServiceImpl;
import net.sf.json.JSONObject;

public class UpdatePwServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	//	System.out.println("updatepw");
		
		IEmployeeService employeeService = new EmployeeServiceImpl();
		
		Map<String,String> errors = new HashMap<String,String>();
		Employee employee = (Employee) req.getSession().getAttribute("employee");
		String empid = employee.getEmpid();
		String sqlpw = employeeService.queryByEmpid(empid).getPassword();
		
		String opw = req.getParameter("opw");
		try {
			if(!checkPw(opw,sqlpw)){
				errors.put("opw", "旧密码错误!");
			}
		} catch (NoSuchAlgorithmException e) {
			//System.out.println("密码检查错误！");
			//e.printStackTrace();
		}
		
		String npw = req.getParameter("npw");
		if (npw.length() < 6 || npw.length() > 15) {
			errors.put("npw", "新密码长度须在6~15之间!");
		}
		
		String rpw = req.getParameter("rpw");
		if(!npw.equals(rpw)){
			errors.put("rpw", "确认密码和新密码不一致!");
		}
		
		if(errors.size()!=0){
			errors.put("flag", "1");
		}else{
			errors.put("flag", "0");
			try {
				npw = EncoderByMd5(npw);
			} catch (NoSuchAlgorithmException e) {
				//System.out.println("密码出错!");
			//	e.printStackTrace();
			}
			
			employeeService.updatePw(empid, npw);
		}
		
		JSONObject json = JSONObject.fromObject(errors);// 使用JSONobject将map对象转换成json对象
		PrintWriter out = resp.getWriter();
		out.print(json);
	}
	
	private String EncoderByMd5(String str) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(str.getBytes());
		byte b[] = md.digest();
		StringBuffer buf = new StringBuffer("");
		for (int offset = 0; offset < b.length; offset++) {
			int i = b[offset];
			if (i < 0)
				i += 256;
			if (i < 16)
				buf.append("0");
			buf.append(Integer.toHexString(i));
		}
		return buf.toString();
	}
	
	public boolean checkPw(String newpw, String oldpw) throws NoSuchAlgorithmException {
//		System.out.println(newpw);
//		System.out.println(oldpw);
//		System.out.println(EncoderByMd5(newpw));
		if (EncoderByMd5(newpw).equals(oldpw))
			return true;
		else
			return false;
	}
}
